<?php

namespace Library;

require_once 'Library/Shortcuts.php';

class Controller {

	private static $_instance;
	
	public static function getInstance() {
		if( self::$_instance == null ) {
			self::$_instance = new Controller();
		}
		return self::$_instance;
	}
	
	private function __construct() {
		spl_autoload_register( array( $this, 'autoload' ) );
	}

	public function autoload( $class ) {
		$class = strtr( $class, '\\', '/' );
		if( file_exists( $class . '.php' ) ) {
			require_once $class . '.php';
		}
	}
	
	public static function dispatch() {
	
		ignore_user_abort( true );
		date_default_timezone_set('UTC');
	
		$sessionConf = Config::get( 'session' );
		session_start( $sessionConf['name'] );
		session_write_close();
	
		$class = isset($_GET['action']) ? $_GET['action'] : 'Main';
		$class = str_replace( '_', '\\', $class );
		
		$class = 'Action\\' . $class;
		
		try {
		
			if( !class_exists( $class, true ) ) {
				header('HTTP/1.0 404 Not Found');
				throw new \Exception( 'Page does not exists : ' . $_GET['action'] );
			}
			
			Auth\Session::getSession();
		
			$class = new $class( $_REQUEST );
			echo $class->process();
		}
		catch( \Exception $e ) {
			if( is_object( $class ) || (is_string( $class ) && class_exists( $class )) ) {
				if( in_array( 'Library\Action\AjaxAction', class_implements( $class ) ) ) {
					header( 'Content-Type: application/json' );
					echo json_encode( array( 
						'status' => 'exception',
						'time' => microtime(true),
						'message' => $e->getMessage()
					) );
					return $this;
				}
			}
			$class = new \Action\Exception( $e );
			echo $class->process();
		}
		
		return $this;
	}
	
	
}
